﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BTM_Client_Application.SupportClasses;
using Client_Server_Interface;
using GMap.NET;

namespace BTM_Client_Application
{
    /// <summary>
    /// Логика взаимодействия для StationInfoControl.xaml
    /// </summary>
    public partial class StationInfoControl : IDisposable
    {

        private readonly ObservableCollection<ListViewItem> _devices;
        private readonly PointLatLng _coordinates;

        private StationInfoControl()
        {
            InitializeComponent();
            UiLanguageChanged();
            _devices = new ObservableCollection<ListViewItem>();
            Style = FindResource("MyPopup") as Style;
            CloseButton.Visibility = Visibility.Hidden;
            
        }

        private StationInfoControl(DeviceTreeItem.StationInfo info) : this()
        {
            StationBox.Content = info.Station;
            RegionBox.Content = info.ParentInfo.Region;
            FzBox.Content = info.BLR;
            try
            {
                AdditionalInfoBox.Text = AliveInfo.DBwork.GetTreeItemTag(info.Station);
            }
            catch (Exception)
            {
            }
            var devices = AliveInfo.MegaDeviceTree.Devices.Where(d => d.DevInfo.ParentInfo.Station == info.Station).ToList();
            DeviceList.Visibility = devices.Count < 1 ? Visibility.Collapsed : Visibility.Visible;
            foreach (IDeviceInterface device in devices)
            {
                var devInfo = new DeviceInStationInfo(device) {ToolTip = DeviceInfoControl.GetOnToolTip(device)};
                devInfo.MouseDoubleClick += DevInfoOnMouseDoubleClick;
                _devices.Add(new ListViewItem {Content = devInfo});
            }
            DeviceList.ItemsSource = _devices;
            
            _coordinates = new PointLatLng(Support.CoordinatesToDouble(info.CoordinatesB),
                                           Support.CoordinatesToDouble(info.CoordinatesA));
            if(string.IsNullOrEmpty(info.Coordinates))
                ShowOnMapButton.Visibility = Visibility.Collapsed;
        }

        //ToImplement
        private void DevInfoOnMouseDoubleClick(object sender, MouseButtonEventArgs mouseButtonEventArgs)
        {
            
            var dev = sender as DeviceInStationInfo;
            AliveInfo.MainWindow.OpenDevice(dev.DeviceInfoControl);
            //return;
            //var f = new MahApps.Metro.Controls.MetroWindow();
            //f.Content = dev.DeviceInfoControl;
            //dev.DeviceInfoControl.Show();
            //f.Show();
            //f.Closed += (o, args) => dev.DeviceInfoControl.Hide();
        }

        public static StationInfoControl GetControl(DeviceTreeItem.StationInfo info)
        {
            var toRet = new StationInfoControl(info);
            return toRet;
        }

        public static ToolTip GetOnToolTip(DeviceTreeItem.StationInfo info)
        {
            var t = new ToolTip {Content = GetControl(info)};
            t.Style = ((StationInfoControl)t.Content).FindResource("MyToolTip1") as Style;
            return t;
        }

        public static Popup GetOnPopup(DeviceTreeItem.StationInfo info, UIElement placementTarget = null)
        {
            var child = GetControl(info);
            child.CloseButton.Visibility = Visibility.Visible;
            var p = new Popup
            {
                Child = child,
            };
            p.Closed += POnClosed;
            p.MouseLeave += (o, eventArgs) =>
            {
                p.IsOpen = false;
            };
            //if (placementTarget != null)
            //{
            //    p.Placement = PlacementMode.Center;
            //    p.PlacementTarget = placementTarget;
            //}
            //else
                p.Placement = PlacementMode.MousePoint;
            p.AllowsTransparency = true;
            child.CloseButton.Click += (sender, args) =>
                {
                    p.IsOpen = false;
                };
            return p;
        }

        private static void POnClosed(object sender, EventArgs eventArgs)
        {
            var c = (sender as Popup).Child as StationInfoControl;
            if(c == null)
                return;
            try
            {
                AliveInfo.DBwork.SetTreeItemTag(c.StationBox.Content.ToString(), c.AdditionalInfoBox.Text);
            }
            catch (Exception ex)
            {
                //AliveInfo.ClientEvents.AddEvent(Res.Rm.GetString("DbError", AliveInfo.CurrentCulture),
                //                                "Data can't be saved:\r\n" + c.AdditionalInfoBox.Text);
                AliveInfo.ClientEvents.AddEvent(Res.Rm.GetString("DbError", AliveInfo.CurrentCulture), ex.Message);
            }
        }

        private void UiLanguageChanged() //Обновление языка интерфейса
        {
            RegionLabel.Content = Res.Rm.GetString("Region", AliveInfo.CurrentCulture) + ":";
            FzLabel.Content = Res.Rm.GetString("FrequencyZone", AliveInfo.CurrentCulture) + ":";
            ShowOnMapButton.Content = " " + Res.Rm.GetString("ShowOnMap") + " ";
            MahApps.Metro.Controls.TextboxHelper.SetWatermark(AdditionalInfoBox,
                                                              Res.Rm.GetString("AdditionalInfo",
                                                                               AliveInfo.CurrentCulture));
        }

        private void ShowOnMapButton_OnClick(object sender, RoutedEventArgs e)
        {
            AliveInfo.SetMapPosition(_coordinates);
        }

        public void Dispose()
        {
        }
    }
}
